package com.deltachi.lateplates;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;

public class SubmitActivity extends Activity {
	Activity self = this;

    private class TimeException extends Exception {
        private String message;
        public TimeException() {
            super();
            this.message = "";
        }
        public TimeException(String msg) {
            super();
            this.message = msg;
        }

        public String getMessage() {
            return this.message;
        }
    }

    private static final String PREFS = "prefsFile";
    private String userName;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.submit);

        userName = getPreferences(MODE_PRIVATE).getString("userName", "");
        final EditText name = (EditText) findViewById(R.id.nameField);
        if (!userName.equalsIgnoreCase("")) {
            name.setText(userName);
        }
        
        name.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            name.setText("");
            name.setTextColor(Color.BLACK);
            }
        });
        
        final EditText comments = (EditText)findViewById(R.id.commentField);
        comments.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            comments.setText("");
            comments.setTextColor(Color.BLACK);
            }
        });

        //Configure submit button action
        final Button submitButton = (Button) findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Set Default name for future running
                userName = name.getText().toString();
                Editor e = getPreferences(Context.MODE_PRIVATE).edit();
                e.putString("userName", userName);
                e.commit();

                final Spinner day = (Spinner)findViewById(R.id.dayField);
                final RadioButton lunch = (RadioButton)findViewById(R.id.lunchButton);
                final RadioButton dinner = (RadioButton)findViewById(R.id.dinnerButton);
                
                //Check for input errors.
                if (name.getText().toString().equalsIgnoreCase("")) {
                	Toast.makeText(SubmitActivity.this, "Please enter your name.", Toast.LENGTH_SHORT).show();
                	return;
                }
                if (day.getSelectedItem().toString().equalsIgnoreCase("Friday") && dinner.isChecked()) {
                	Toast.makeText(SubmitActivity.this, "Sorry, there is no Friday dinner available.", Toast.LENGTH_SHORT).show();
                	return;
                }
                
                //HTTP Client
                DefaultHttpClient httpclient = new DefaultHttpClient();
                
                //Get user account
                AccountManager mgr = AccountManager.get(getApplicationContext()); 
                Account[] accounts = mgr.getAccountsByType("com.google"); 
                Account account = accounts[0];
                
                //HTTP Post
                HttpPost httppost = new HttpPost("http://dxlateplates.appspot.com/submitLatePlate"); 
              
                try {  
                    // Add your data  
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
                    nameValuePairs.add(new BasicNameValuePair("userName", account.name));  
                    nameValuePairs.add(new BasicNameValuePair("name", name.getText().toString()));  
                    nameValuePairs.add(new BasicNameValuePair("day", day.getSelectedItem().toString()));
                    
                    //Get day value
                    String type = "";
                    if (lunch.isChecked()) {
                    	type = "1";
                    } else if (dinner.isChecked()) {
                    	type = "2";
                    }
                    nameValuePairs.add(new BasicNameValuePair("type", type));  
                    
                    //Get comments
                    nameValuePairs.add(new BasicNameValuePair("comments", comments.getText().toString()));
              
                    // Execute HTTP Post Request  
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);  
                      
                } catch (ClientProtocolException ce) {  
                	ce.printStackTrace();
                } catch (IOException ie) {  
                    ie.printStackTrace(); 
                }  
                
                Toast.makeText(SubmitActivity.this, "Late plate submitted successfully.", Toast.LENGTH_LONG).show();
                return;
                
            }
        });


    }

    //Function that sends texts
    private void sendSMS(String phoneNumber, String message)
    {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }

}
